

"""test ldap connection by using ldap3"""

from ldap3 import Server, Connection, ALL


def test_201_86():
    print("\ntest LDAP connection to 10.99.201.86")
    server = Server('10.99.201.86', port=10389, get_info=ALL)
    print('server = %s'%server)
    print('server.info = %s'%server.info)
    with Connection(server, user='uid=admin,ou=system', 
                    password='admin86xx') as conn:
        conn.bind()
        print('conn bind')
        #print('server.info = %s'%server.info)
        conn.search('ou=users,ou=plmdeploy,dc=lenovo,dc=com', 
                    '(objectclass=person)', attributes=['uid', 'mail', 'cn'])
        if hasattr(conn, 'entries'):
            entries = conn.entries
            for entry in entries:
                print('entry: uid=%s, mail=%s'%(entry['uid'], entry['mail']))


def test_lenovo_com():
    print("\ntest LDAP connection to lenovo.com")
    server = Server('lenovo.com', port=3268)
    print('server = %s'%server)
    with Connection(server, 
                    user='CN=adplm,OU=Service Accounts,DC=lenovo,DC=com', 
                    password='ZpGf-5494') as conn:
        print('conn = %s'%conn)
        conn.bind()
        print('conn bind')
        #print('server.info = %s'%server.info)
        print('start to print all usres:')
        user_ids = ['zhoujj', 'heyan', 'mengqq', 'zhangymd']
        for user_id in user_ids:
            conn.search('CN=%s,OU=Beijing,OU=China,OU=User Accounts,DC=lenovo,DC=com'%user_id, 
                        '(objectclass=person)', 
                        attributes=['distinguishedName', 'mail', 'cn'])
            if hasattr(conn, 'entries') and conn.entries:
                entry = conn.entries[0]
                print('distinguishedName=%s, mail=%s, cn=%s'
                      %(entry['distinguishedName'], entry['mail'], entry['cn']))
            else:
                print('%s not found'%user_id)


if __name__ == '__main__':
    print("test ldap3")
    test_201_86()
    test_lenovo_com()
    print("\ntest end")